package authentication

import (
	"MoSkeleton/framework/core/config/properties_gin"
	"MoSkeleton/framework/core/consts"
	"MoSkeleton/framework/core/dto/response"
	"MoSkeleton/framework/mo_gin"
	"MoSkeleton/framework/mo_gin/middleware/utils"
	fu "MoSkeleton/framework/utils"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"go.uber.org/zap"
	"strconv"
	"time"
)

func doJwtAuth(c *gin.Context) AuthFlowContinue {

	jwtProperty := mo_gin.CommonGin.AuthGroup.Jwt
	token, ok := utils.GetJwtToken(c)
	if !ok {
		return doWhenNoJwtToken(c, jwtProperty)
	}
	return doWhenJwtToken(c, jwtProperty, token)
}

func doWhenJwtToken(c *gin.Context, jwtProperty properties_gin.JwtProperty, token string) AuthFlowContinue {
	c.Set(consts.GinContext_AuthType_Key, consts.Request_Token_Type_Jwt)
	j := fu.NewJWT(&mo_gin.CommonGin.AuthGroup.Bearer)
	// parseToken 解析token包含的信息
	claims, err := j.ParseToken(token)
	if err != nil {
		if errors.Is(err, jwt.ErrTokenExpired) {
			//"授权已过期"
			mo_gin.MoLogger.Error("授权已过期", zap.String("token", token))
			response.ErrorTokenAuthFail(c)
			return false
		}
		mo_gin.MoLogger.Error("授权已过期", zap.Error(err))
		response.ErrorTokenAuthFail(c)
		return false
	}

	// 已登录用户被管理员禁用 需要使该用户的jwt失效 此处比较消耗性能 如果需要 请自行打开
	// 用户被删除的逻辑 需要优化 此处比较消耗性能 如果需要 请自行打开

	//if user, err := userService.FindUserByUuid(claims.UUID.String()); err != nil || user.Enable == 2 {
	//	_ = jwtService.JsonInBlacklist(system.JwtBlacklist{Jwt: token})
	//	response.FailWithDetailed(gin.H{"reload": true}, err.Error(), c)
	//	c.Abort()
	//}
	c.Set(consts.GinContext_Claims_Key, claims)
	c.Set(consts.GinContext_Token_Key, token)
	if claims.ExpiresAt.Unix()-time.Now().Unix() < claims.BufferTime {
		dr, _ := fu.ParseDuration(mo_gin.CommonGin.AuthGroup.Jwt.ExpiresTime)
		claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(dr))
		newToken, _ := j.CreateTokenByOldToken(token, *claims)
		newClaims, _ := j.ParseToken(newToken)
		c.Header("new-token", newToken)
		c.Header("new-expires-at", strconv.FormatInt(newClaims.ExpiresAt.Unix(), 10))
		//if global.GVA_CONFIG.System.UseMultipoint {
		//	RedisJwtToken, err := jwtService.GetRedisJWT(newClaims.Username)
		//	if err != nil {
		//		global.GVA_LOG.Error("get redis jwt failed", zap.Error(err))
		//	} else { // 当之前的取成功时才进行拉黑操作
		//		_ = jwtService.JsonInBlacklist(system.JwtBlacklist{Jwt: RedisJwtToken})
		//	}
		//	// 无论如何都要记录当前的活跃状态
		//	_ = jwtService.SetRedisJWT(newToken, newClaims.Username)
		//}
	}
	c.Next()

	if newToken, exists := c.Get("new-token"); exists {
		c.Header("new-token", newToken.(string))
	}
	if newExpiresAt, exists := c.Get("new-expires-at"); exists {
		c.Header("new-expires-at", newExpiresAt.(string))
	}
	return false
}

func doWhenNoJwtToken(context *gin.Context, jwtProperty properties_gin.JwtProperty) AuthFlowContinue {
	if ifMatchPath(context.Request.RequestURI, jwtProperty.NoForceAuthUrls) {
		return true
	} else {
		context.Set(consts.GinContext_AuthType_Key, consts.Request_Token_Type_Jwt)
		response.ErrorTokenAuthFail(context)
		return false
	}
}
